class Solution
{
public:
    int orangesRotting(vector<vector<int>> &grid)
    {
        int m = grid.size();
        int n = grid[0].size();

        queue<pair<int, int>> q;
        int fresh = 0;
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (grid[i][j] == 2)
                {
                    q.emplace(i, j);
                }
                else if (grid[i][j] == 1)
                {
                    ++fresh;
                }
            }
        }

        int t = 0;
        vector<pair<int, int>> dirs{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        while (!q.empty())
        {

            int qSize = q.size();
            for (int _ = 0; _ < qSize; ++_)
            {
                auto [x, y] = q.front();
                q.pop();
                for (auto [dx, dy] : dirs)
                {
                    int nx = x + dx, ny = y + dy;
                    if (nx >= 0 & nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1)
                    {
                        grid[nx][ny] = 2;
                        q.emplace(nx, ny);
                        --fresh;
                    }
                }
            }

            if (!q.empty())
            {
                ++t;
            }
        }
        return fresh == 0 ? t : -1;
    }
};